import pymysql

from configs.load_configs import ConfigLoader


class MySQLDB(object):

    def __init__(self):
        config = ConfigLoader.load_mysql_config()
        # 连接到MySQL数据库
        self.conn = pymysql.connect(
            host=config["host"],
            port=config["port"],
            user=config["user"],
            password=config["password"],
            database=config["database"],
            charset=config["charset"],
            conv={pymysql.FIELD_TYPE.STRING: str},
            cursorclass=pymysql.cursors.DictCursor
        )

    def query(self, query):
        # 创建游标对象
        cursor = self.conn.cursor()
        # 执行查询
        cursor.execute(query)
        # 获取查询结果
        results = cursor.fetchall()
        # 关闭游标和连接
        cursor.close()
        return results

    def close(self):
        self.conn.close()


if __name__ == "__main__":
    db = MySQLDB()
    result = db.query("SELECT * FROM contracts WHERE created_at >= '2023-05-01' AND created_at < '2024-01-31';")
    print(result)
